<?php
if(check_file("myapikeys.php"))
	include_once("myapikeys.php");
else
	exit();	
/*--------------------------------------------------------------------------------------------------
 This File contains all functions necessary for sending an API to perform the available
 TringMe operations as mentioned in the documentation. 
 
 IMPORTANT: All functions are dependent on the a base API URL 
            http://login.tringme.com/api.php?  which is invoked to perform the operation.
--------------------------------------------------------------------------------------------------*/
$tringmebaseurl  = "http://login.tringme.com/api.php?";

/*--------------------------------------------------------------------------------------------------
Function Name: TringMeAPI                                                                     
                                                                                                      
Descripton: Performs the requested API operation                                                                         
                                                                                                     
Prototype: TringMeAPI($parameters, $privatekey, &$result)     
                                                                                                      
Parameters:                                                                                           
           $privatekey- User's Private Key which is issued by TringMe.                                 
           $parameters - Parameters specific to the operation
		   $result- Contains the response information.                                                                    

Dependencies:                                                                                        
           None 
                                                                                         
Return Values:                                                                                       
           True- If operation is successful.                                                        
           False- If operation failed.                                                             

Side Effects:                                                                                        
           None                                    
                                                                                                      
--------------------------------------------------------------------------------------------------*/
function TringMeAPI($parameters,&$result) {
	global $privatekey, $publickey;
	$parameters['apikey']=$publickey;
	$apiuri=CreateAPIURL($parameters, $privatekey);
	$response = GetAPIResponse($apiuri);
    return TringMeParseResponse($response, $result);
}

/*--------------------------------------------------------------------------------------------------
Function Name: TringMeParseResponse                                                                     
                                                                                                      
Descripton: Converts the response into function usable format for programming convenience. 
               
Prototype: boolean TringMeParseResponse($response, &$result)     
                                                                                                      
Parameters:                                                                                           
           $response - The response to be parsed.                                 
		   $result- Contains the parsed response.                                                                    

Return Values:                                                                                       
           True- If the response was a success.                                                        
           False- If the response was a failure.                                                             

--------------------------------------------------------------------------------------------------*/
function TringMeParseResponse($response, &$result) {
    
    $result = '';
    $resppara = explode(' ', $response, 2);
    if(isset($resppara[1])) {
        $result = $resppara[1];
    }

    if('OK' == $resppara[0]) {
        return true;
    }
    if('OKJ' == $resppara[0]) {
    	$result = json_decode($resppara[1], true);
        if(null!=$result)
            return true;
    }
    return false;
}

/*--------------------------------------------------------------------------------------------------
Function Name: GetAPIResponse                                                                     
                                                                                                      
Descripton: Reads the response from TringMe URL for the request made.
               
Prototype: string GetAPIResponse($url)     
                                                                                                      
Parameters:                                                                                           
           $url - URL of the API being invoked.                                 

Return Values:                                                                                       
           Returns the response
--------------------------------------------------------------------------------------------------*/
function GetAPIResponse($url) {
    
    $opts = array(
        'http'=>array(
        'method'=>"GET",
        'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
                  )
        );

    $context = stream_context_create($opts);
    $response = 'FAILED';
    $sock=fopen($url, 'r', false, $context);
    if ($sock) {
        $response='';
        while (!feof($sock))
           $response.=fgets($sock, 4096);

        fclose($sock);
    }
    return $response;
}

/*--------------------------------------------------------------------------------------------------
Function Name: GetSignature                                                                     
                                                                                                      
Descripton: string Creates the MD5 signature based on the passed parameters. 
               
Prototype: GetSignature($params_array, $privatekey)     
                                                                                                      
Parameters:                                                                                           
           $params_array - Parameters                                 
		   $privatekey - The private key.                                                                    

Return Values:                                                                                       
           The MD5 signature.                                                             

--------------------------------------------------------------------------------------------------*/
function GetSignature($params_array, $privatekey) {

    $str='';
    ksort($params_array);
    foreach($params_array as $key=>$val) {
        $str .="$key=$val";
    }
    $str.= $privatekey;
    return md5($str);
}

/*--------------------------------------------------------------------------------------------------
Function Name: CreateAPIURL                                                                     
                                                                                                      
Descripton: Creates the request URL for the API being invoked with all the parameters and signature
            appended to the URL as required. 
               
Prototype: string CreateAPIURL($params_array, $privatekey)     
                                                                                                      
Parameters:                                                                                           
           $params_array - Parameters                                 
		   $privatekey - The private key.                                                                    

Dependencies:                                                                                        
           None 
                                                                                         
Return Values:                                                                                       
           The URL that is constructed.                                                             

Side Effects:                                                                                        
           None                                    
                                                                                                      
--------------------------------------------------------------------------------------------------*/
function CreateAPIURL($params_array, $privatekey) {

    global $tringmebaseurl;    
    $signature = GetSignature($params_array, $privatekey);
    $uri = $tringmebaseurl;
    foreach($params_array as $key=>$val) {   
        $uri .= "$key=" . urlencode($val) . '&';    
    }

    $uri .= "sig=$signature";        
    return $uri;
}

// Helper function to ensure that the developer includes his API keys.
function check_file($file_name) {
	if(file_exists($file_name)) {
		$str=file_get_contents($file_name);	
		if(strstr($str,"\$privatekey")) {
			if(strstr($str,"\$publickey"))
				return true;
			else
				echo "ERROR: Please define your public key. If you don't have one then send a mail to <a href='mailto:support@tringme.com'>support@tringme.com</a>";
		}
		else {
			echo "ERROR: Please define your private key. If you don't have one then send a mail to <a href='mailto:support@tringme.com'>support@tringme.com</a>";
		}
	}
	else {
		echo "ERROR: File $file_name doesnot exist";
	}
	return false;
}
?>
